package br.indt.framework.threadpool;

import java.util.Vector;


public class PriorityQueue {
	
	/**
	 * PRIORITY_1 is the highest priority queue
	 */
	public static final byte MAX_PRIORITY = 1;
	public static final byte PRIORITY_0 = 0;
	public static final byte PRIORITY_1 = 1;
	
	/**
	 * Will have MAX_PRIORITY + 1 rows.
	 * Each row will point to a queue of requests  
	 */
	private Vector[] queue = null;
	
	public PriorityQueue() {
		queue = new Vector[MAX_PRIORITY + 1];
		for(int i=0; i<= MAX_PRIORITY; i++) {
			queue[i] = new Vector();
		}
	}
	
	public void addItem(Object obj, byte priority) {
		synchronized (this) {
			queue[priority].addElement(obj);
			notify();
		}
	}
	
	/**
	 * this queue is only handled by ThreadPoolManager(singleton), so
	 * no need to synchronize 
	 * 
	 * @return
	 */
	public Object getItem() {
		for(int i=MAX_PRIORITY; i >= 0; i--) {
			Vector vt = queue[i];
			if(vt.size()>0) {
				synchronized (queue) {
					Object obj = vt.elementAt(0);
					vt.removeElementAt(0);
					return obj;
				}
			}
		}
		return null;
	}
	
	public void clearAll() {
		for(int i=MAX_PRIORITY; i >= 0; i--) {
			Vector vt = queue[i];
			vt.removeAllElements();
		}
	}
	
	public void clearAll(byte priority) {
		queue[priority].removeAllElements();
	}
	
	public synchronized ThreadPoolTask removeItem(int id) {
		for(int i=MAX_PRIORITY; i >= 0; i--) {
			Vector vt = queue[i];
			for(int j=0; j < vt.size(); j++) {
				ThreadPoolTask task = (ThreadPoolTask)vt.elementAt(j);
				if(task.getId() == id) {
					vt.removeElementAt(j);
					return task;
				}
			}
		}
		return null;
	}
}
